<template>
  <div>
    <el-table
      :data="tableData1" 
      ref="tableRef" 
      row-key="id" 
      style="width: 100%" 
      :height="height" 
      :size="size"
      @row-click="handleRowClick"
    >
      <el-table-column 
        show-overflow-tooltip
        v-for="(i, index) in col" 
        :key="index + '' + Math.random()" 
        :type="i.type"
        :prop="i.prop" 
        :label="i.label" 
        :fixed="i.fixed" 
        align="center"
      >
        <template slot-scope="scope">
          <slot :name="i.prop" :row="scope.row">
            <span v-if="i.label.includes('时间')||i.label.includes('日期')">{{ parseTime(scope.row[i.prop], i.isShowTime ? '{y}-{m}-{d}' : '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            <span v-else-if="i.label.includes('颜色')"><el-color-picker disabled v-model="scope.row[i.prop]"></el-color-picker></span>
            <span v-else-if="i.type === 'index'">{{ scope.$index + 1 }}</span>
            <span v-else-if="i.isDict">{{ dictFormat(scope.row, i.prop, i.dictInd) }}</span>
            <span v-else>{{ scope.row[i.prop] }}</span>
          </slot>
        </template>
      </el-table-column>
      
      <slot name="operate"></slot>
    </el-table>
  </div>
</template>

<script>
// col 类型 isDict 是否是字典 如果是字典就得传字典list：dictlist

import Sortable from 'sortablejs'
export default {
  name: 'DropTable',
  props: {
    tableData: {
      type: Array,
      default: () => [],
      required: true
    },
    height: {
      type: Number,
      default: null
    },
    col: {
      type: Array,
      default: () => []
    },
    size: {
      type: String,
      default: 'medium'
    },
    // 字典列表
    dictlist: {
      type: Array,
      default: ()=> []
    },
  },
  data() {
    return {
      tableData1: [],
      multipleSelection: []
    }
  },
  watch: {
    tableData: {
      handler(val) {
        this.tableData1 = val;
      },
      immediate: true
    }
  },
  mounted () {
    document.body.ondrop = function(event) {
       // 阻止默认行为
      event.preventDefault();
      event.stopPropagation();
    };
    this.$nextTick(() => {
      this.rowDrop();
      this.columnDrop();
    })
    this.tableData1 = this.tableData;
    // console.log(this.dictlist);
  },
  methods: {
    // 行拖拽
    rowDrop () {
      const elTableBody = this.$refs.tableRef.$el.querySelector(
        ".el-table__body-wrapper tbody"
      );

      Sortable.create(elTableBody, {
        animation: 150,
        onEnd: (evt) => {
          // 获取拖拽的行数据
          const movedRow = this.tableData1[evt.oldIndex];
          
          // 临时数组保存排序后的数据
          const updatedData = [...this.tableData1];
          updatedData.splice(evt.oldIndex, 1); // 移除旧位置
          updatedData.splice(evt.newIndex, 0, movedRow); // 插入新位置

          // 触发响应式更新
          this.tableData1 = [];  // 清空tableData
          this.$nextTick(() => {
            this.tableData1 = updatedData; // 重新赋值
            requestAnimationFrame(() => {
              this.$refs.tableRef.doLayout(); // 确保表格布局更新
            })
          });
        },
      });
    },
    // 列拖拽
    columnDrop () {
      const elTableHeader = this.$refs.tableRef.$el.querySelector(
        ".el-table__header-wrapper tr"
      );
      Sortable.create(elTableHeader, {
        animation: 150,
        onEnd: (evt) => {
          const movedColumn = this.col.splice(evt.oldIndex, 1)[0];
          this.col.splice(evt.newIndex, 0, movedColumn);
          // console.log(this.col);
          // this.$refs.tableRef.doLayout(); // 强制刷新表格布局
          // 延迟调用 doLayout，减少闪烁
          requestAnimationFrame(() => {
            this.$refs.tableRef.doLayout();
          });
        },
        filter: '.non-draggable',  // 指定不允许拖动的列
        preventOnFilter: false     // 避免事件冲突
      });
    },
    // 字典格式化
    dictFormat (row, prop, ind) {
      let name = ''
      this.dictlist[ind].forEach(item => {
        if(item.value == row[prop]){
          name = item.label
        }
      })
      return name
    },
    handleRowClick(row) {
      this.$emit('handleRowClick', row)
    }
  }
}
</script>

<style scoped>
::v-deep.el-table .el-table__cell.gutter {
  display: none;
}

/deep/.el-table__fixed::before {
  height: 0px;
}
/deep/.el-table th .cell {
  /* white-space: nowrap; 
  overflow: visible;   
  text-overflow: unset;  */
}
/* // 滚动条的宽度 */
/* ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px; 
  height: 6px; 
} */
/* // 滚动条的滑块 */
/* ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 4px;
} */
</style>
<style lang="scss" scoped>

</style>